﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using BLFacade.entities;
using BLFacade;

namespace ProjectUI
{
    public partial class EmployeeForm : Form
    {
        private bool passchanged = false;
        private Regex emailTest = new Regex(@"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$");
        private IEmployee employee;
        
        public EmployeeForm()
        {
            InitializeComponent();
            btnEdit.Visible = false;
            btnDismiss.Visible = false;
            btnTasks.Visible = false;
            cmbxAppointments.Enabled = true;
            nudSalaryModifier.Enabled = true;
            cmbxAppointments.DataSource = FacadeHolder.DataFacade.GetAppointments();
            grbxInfo.Controls.Remove(lblAcceptDate);
            grbxInfo.Controls.Remove(lblAcceptValue);
            grbxInfo.Controls.Remove(lblRejectDate);
            grbxInfo.Controls.Remove(lblRejectValue);
        }

        public EmployeeForm(IEmployee employee)
        {
            InitializeComponent();
            this.employee = employee;
            grbxInfo.Enabled = false;
            grbxCredentials.Enabled = false;
            txtFirstName.Text = employee.FirstName;
            txtMiddleName.Text = employee.MiddleName;
            txtLastName.Text = employee.LastName;
            txtEmail.Text = employee.Email;
            txtPhoneNumber.Text = employee.PhoneNumber;
            dateBirth.Value = employee.DateofBirth;
            lblAcceptValue.Text = employee.AcceptDate.ToShortDateString();
            cmbxAppointments.DataSource = FacadeHolder.DataFacade.GetAppointments();
            cmbxAppointments.SelectedValue = employee.Appointment.Name;
            nudSalaryModifier.Value = (decimal)employee.SalaryModifier;
            if (employee.RejectDate.HasValue)
            {
                lblRejectValue.Text = employee.RejectDate.Value.Date.ToShortDateString();
                btnDismiss.Visible = false;
            }
            else
            {
                grbxInfo.Controls.Remove(lblRejectDate);
                grbxInfo.Controls.Remove(lblRejectValue);
            }
            txtUsername.Text = employee.Credentials.Username;
            if (!FacadeHolder.UserFacade.IsHRManager()) btnDismiss.Visible = false;
            else btnTasks.Visible = false;
            btnCreate.Text = "Submit";
            btnCreate.Enabled = false;
            this.Text = String.Format("Information about {0}", employee.FullName);
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            btnCreate.Enabled = grbxCredentials.Enabled = grbxInfo.Enabled = !grbxInfo.Enabled;
            if (FacadeHolder.UserFacade.IsHRManager())
            {
                cmbxAppointments.Enabled = true;
                nudSalaryModifier.Enabled = true;
            }
        }

        private void txtPassword_TextChanged(object sender, EventArgs e)
        {
            passchanged = true;
        }

        private void txt_Validating(object sender, CancelEventArgs e)
        {
            if (String.IsNullOrWhiteSpace(((TextBox)sender).Text))
            {
                errorFormProvider.SetError((TextBox)sender, "This field mustn't be empty");
            }
            else
            {
                errorFormProvider.SetError((TextBox)sender, "");
            }
        }

        private void txtPassword_Validating(object sender, CancelEventArgs e)
        {
            if (txtPassword.Text.Length < 8)
            {
                errorFormProvider.SetError(txtPassword, "Password must contain a minimum of 8 characters");
            }
            else
            {
                errorFormProvider.SetError(txtPassword, "");
            }
        }

        private void dateBirth_Validating(object sender, CancelEventArgs e)
        {
            if (dateBirth.Value > DateTime.Now.AddYears(16))
            {
                errorFormProvider.SetError(dateBirth, "Incorrect date of birth");
            }
            else
            {
                errorFormProvider.SetError(dateBirth, "");
            }
        }

        private void txtEmail_Validating(object sender, CancelEventArgs e)
        {
            if (!emailTest.IsMatch(txtEmail.Text))
            {
                errorFormProvider.SetError(txtEmail, "Incorrect e-mail");
            }
            else
            {
                errorFormProvider.SetError(txtEmail, "");
            }
        }

        private bool IsValid()
        {
            foreach (Control c in grbxInfo.Controls)
            {
                if (!String.IsNullOrEmpty(errorFormProvider.GetError(c))) return false;
            }
            foreach (Control c in grbxCredentials.Controls)
            {
                if (!String.IsNullOrEmpty(errorFormProvider.GetError(c))) return false;
            }
            return true;
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            if (!IsValid()) return;
            if (employee == null)
            {
                FacadeHolder.DataFacade.CreateEmployee(txtFirstName.Text, txtMiddleName.Text, txtLastName.Text, txtEmail.Text, txtPhoneNumber.Text, dateBirth.Value, (IAppointment)cmbxAppointments.SelectedItem, (double)nudSalaryModifier.Value, txtUsername.Text, txtPassword.Text);
            }
            else
            {
                employee.FirstName = txtFirstName.Text;
                employee.MiddleName = txtMiddleName.Text;
                employee.LastName = txtLastName.Text;
                employee.Email = txtEmail.Text;
                employee.PhoneNumber = txtPhoneNumber.Text;
                employee.DateofBirth = dateBirth.Value;
                employee.Appointment = (IAppointment)cmbxAppointments.SelectedItem;
                employee.SalaryModifier = (double)nudSalaryModifier.Value;
                employee.Credentials.Username = txtUsername.Text;
                if (passchanged) employee.Credentials.Password = txtPassword.Text;
            }
            FacadeHolder.DataFacade.SaveChanges();
            this.Close();
        }

        private void btnTasks_Click(object sender, EventArgs e)
        {
            TaskListForm tasks = new TaskListForm(employee);
            tasks.MdiParent = this.MdiParent;
            tasks.Show();
        }

        private void btnDismiss_Click(object sender, EventArgs e)
        {
            employee.Dismiss();
            FacadeHolder.DataFacade.SaveChanges();
            this.Close();
        }

        private void txtUsername_Validating(object sender, CancelEventArgs e)
        {
            if (String.IsNullOrWhiteSpace(txtUsername.Text))
            {
                errorFormProvider.SetError(txtUsername, "This field mustn't be empty");
            }
            else if (FacadeHolder.DataFacade.IsUniqueUsername(txtUsername.Text))
            {
                errorFormProvider.SetError(txtUsername, "Username must be unique");
            }
            else
            {
                errorFormProvider.SetError((TextBox)sender, "");
            }
        }
    }
}
